package com.seecen.cywbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.cywbackend.mapper.DynamicMapper;
import com.seecen.cywbackend.pojo.Favorite;
import com.seecen.cywbackend.service.FavoriteService;
import com.seecen.cywbackend.mapper.FavoriteMapper;
import com.seecen.cywbackend.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
* @author lenovo
* @description 针对表【t_favorite(用户收藏表（支持交易、产品、动态）)】的数据库操作Service实现
* @createDate 2025-03-23 22:32:09
*/
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite>
    implements FavoriteService{
    @Resource
    private FavoriteMapper favoriteMapper;
    @Resource
    private DynamicMapper dynamicMapper;
    @Override
    @Transactional
    public Result dynamicFavorite(Long userId, Integer dynamicId) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
                .eq(Favorite::getTargetId, dynamicId)
                .eq(Favorite::getTargetType, 3); // 3代表动态类型

        Favorite favorite = favoriteMapper.selectOne(wrapper);
        if (favorite != null) {
            favoriteMapper.deleteById(favorite.getId());
            dynamicMapper.decrementFavoriteCount(dynamicId);
        } else {
            Favorite newFavorite = new Favorite();
            newFavorite.setUserId(userId);
            newFavorite.setTargetId(dynamicId);
            newFavorite.setTargetType(3);
            newFavorite.setCreateTime(new Date());
            favoriteMapper.insert(newFavorite);
            dynamicMapper.incrementFavoriteCount(dynamicId);
        }
        return Result.ok(null);
    }
}




